package com.xiaoyu.lanling.common.config;

import android.content.Context;
import android.graphics.Typeface;

import androidx.annotation.NonNull;
import androidx.emoji.text.EmojiCompat;
import androidx.emoji.text.MetadataRepo;

import com.xiaoyu.net.OkHttpClientSupplier;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

import in.srain.cube.cache.DiskFileUtils;
import in.srain.cube.concurrent.AppThreads;
import okhttp3.Request;
import okhttp3.Response;
import okio.BufferedSink;
import okio.Okio;

public class CPBundledEmojiCompatConfig extends EmojiCompat.Config {
    public CPBundledEmojiCompatConfig(@NonNull Context context) {
        super(new CPBundledMetadataLoader(context));
    }

    private static class CPBundledMetadataLoader implements EmojiCompat.MetadataRepoLoader {
        private final Context mContext;

        CPBundledMetadataLoader(@NonNull Context context) {
            mContext = context.getApplicationContext();
        }

        @Override
        public void load(@NonNull EmojiCompat.MetadataRepoLoaderCallback loaderCallback) {
            AppThreads.runOnIOThread(() -> {
                try {
                    File downloadedFile = new File(mContext.getCacheDir(), "cp.ttf");
                    if (!downloadedFile.exists()) {
                        loadTTFResFromServer(mContext, loaderCallback);
                    } else {
                        loadTTFResFromLocal(mContext, loaderCallback);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    loaderCallback.onFailed(e);
                }
            });
        }
    }

    private static void loadTTFResFromServer(Context context, @NonNull EmojiCompat.MetadataRepoLoaderCallback loaderCallback) throws Exception {
        Request request = new Request.Builder().url("http://res-cdn.myrightone.com/res/NotoColorEmojiCompat.ttf")
                .build();
        Response response = null;
        Response response2 = null;
        try {
            response = OkHttpClientSupplier.get().newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
            loaderCallback.onFailed(e);
        }

        try {
            response2 = OkHttpClientSupplier.get().newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
            loaderCallback.onFailed(e);
        }

        File downloadedFile = new File(DiskFileUtils.wantFilesPath(context, false), "cp.ttf");
        BufferedSink sink = Okio.buffer(Okio.sink(downloadedFile));
        sink.writeAll(response2.body().source());

        ByteBuffer buffer = ByteBuffer.wrap(response.body().bytes());
        try {
            final MetadataRepo resourceIndex = MetadataRepo.create(Typeface.createFromFile(downloadedFile), buffer);
            loaderCallback.onLoaded(resourceIndex);
        } catch (Throwable e) {
            e.printStackTrace();
            loaderCallback.onFailed(e);
        }
        response.body().close();
        response2.body().close();
    }

    private static void loadTTFResFromLocal(Context context, @NonNull EmojiCompat.MetadataRepoLoaderCallback loaderCallback) throws Exception {
        File downloadedFile = new File(DiskFileUtils.wantFilesPath(context, false), "cp.ttf");
        try {
            final MetadataRepo resourceIndex = MetadataRepo.create(Typeface.createFromFile(downloadedFile), new FileInputStream(downloadedFile));
            loaderCallback.onLoaded(resourceIndex);
        } catch (Throwable e) {
            e.printStackTrace();
            loaderCallback.onFailed(e);
        }
    }
}
